package com.debao.system.domain.wechat;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.amazonaws.auth.SdkClock;
import com.debao.common.constant.Constants;
import com.debao.common.constant.WechatConstants;
import com.debao.common.core.domain.entity.SysUser;
import com.debao.common.wechat.WechatUtils;
import com.debao.system.service.IConfigService;
import com.debao.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


/**
 * 关注公众号/取消关注公众号
 */
@Service
@Slf4j
public class WechatAccountServiceImpl implements WechatAccountService{

    @Autowired
    private IConfigService configService;

    @Autowired
    private ISysUserService userService;

    /**
     * 获取用户基本信息的url
     */
    public static String ACCOUNT_URL = "https://api.weixin.qq.com/cgi-bin/user/info";


    /**
     * 关注公众号
     * @param openId
     */
    @Override
    public void subscribeMPUserInfo(String openId) {
        String accountToken = getAccountToke();
        Map<String, Object> requestParameters = new HashMap<>();
        requestParameters.put("access_token", accountToken);
        requestParameters.put("openid",openId);
        requestParameters.put("lang", "zh_CN");

        JSONObject response = JSONUtil.parseObj(HttpUtil.get(ACCOUNT_URL, requestParameters));
        String unionid = response.getStr("unionid");
        //更新用户信息
        userService.updateOpenIdByUnionId(unionid, openId, Constants.FOLLOW_STATUS_Y);
    }

    /**
     * 取消关注公众号
     * @param openId
     */
    @Override
    public void unsubscribeMPUserInfo(String openId) {
        //更新用户信息
        userService.updateOpenIdByOpenId(openId, Constants.FOLLOW_STATUS_N);
    }

    /**
     * 获取微信公众号token
     * @return
     */
    public String getAccountToke(){
        //微信公众号appId
        String accountAppId = configService.selectValueByKey(WechatConstants.APP_ACCOUNT_ID);
        //微信公众号secret
        String accountSecret = configService.selectValueByKey(WechatConstants.APP_ACCOUNT_SECRET);
        //微信公众号token
        String accountToken = WechatUtils.getAccountToken(accountAppId, accountSecret);
        return accountToken;
    }
}
